package com.qf.student.utils;

import com.qf.student.common.Const;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YaoJiXing
 * created 2022/11/22 17:45
 */
public class TokenUtils {

    public static String createJwtToken(String key, Object value) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, value);

        long now = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder()
                .addClaims(map)
                .signWith(SignatureAlgorithm.HS256, Const.SECRET)
                .setIssuedAt(new Date(now))
//                .setExpiration(new Date(now + Const.HAFT_HOUR));
                .setExpiration(new Date(now + Const.HAFT_HOUR));
        return jwtBuilder.compact();
    }

    public static Claims getTokenValue(String token) {
        return (Claims) Jwts.parser()
                .setSigningKey(Const.SECRET)
                .parse(token)
                .getBody();
    }

    public static Integer getUserId(HttpServletRequest request) {
        String jwt = request.getHeader(Const.AUTHORIZATION);
        //取得JWT-Token中的值
        Map<String,Object> data = (Map<String, Object>) getTokenValue(jwt).get("user");
        //通过Map取值
        return (Integer) data.get("userId");
    }
}
